const Base = require('./base.js');

module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.money = this.model("system/money");
		this.asset = this.model("system/asset");
	}
	async indexAction() {
		if(this.isGet) {
			return this.display();
		}

		let posts = this.post();
		let where = {};
		
		if(!think.isEmpty(posts.type)) {
			where.type = posts.type;
		}
		if(!think.isEmpty(posts.status)) {
			where['t.status'] = posts.status;
		}
		if(!think.isEmpty(posts.change)) {
			where.change = posts.change;
		}

		let fields = "id, type, create_time, amount, balance, note, status, change, user_id";
		const data = await this.money.joinUserTable(posts,where,fields);
		return this.json(data);

	}

	async statusAction() {
		let id = this.post("id");
		let status = this.post("status");
		let row = "";
		let self = this;
		await this.money.transaction(async() => {
			row = await self.money.setOne(id, {
				status: status
			});
			let money = await self.money.findOne(id);

			if(status == 1) {
				console.log(money)
				switch(money.type) {
					case 1:
						await self.asset.db(self.money.db()).where({user_id: money.user_id}).increment('amount', money.amount);
						//充值成功，金钱资产加上充值金额
						break;
					case 4:
						await self.asset.db(self.money.db()).where({user_id: money.user_id}).increment('amount', money.amount);
						await self.asset.db(self.money.db()).where({user_id: money.user_id}).decrement('rebate', money.amount);
						//分红成功，金钱资产加上分红金额，预估分红减去分红金额
						break;
					default:
					console.log("9999999")
						break;
				}

			}
			if(status == -1) {
				console.log(money)
				switch(money.type) {

					case 2:
						await self.asset.db(self.money.db()).where({user_id: money.user_id}).increment('amount', money.amount);
						//支付失败，金钱资产加回支付金额
						break;
					case 3:
						await self.asset.db(self.money.db()).where({user_id: money.user_id}).increment('amount', money.amount);
						//提现失败，金钱资产加回提现金额
						break;
					case 4:
						await self.asset.db(self.money.db()).where({user_id: money.user_id}).decrement('rebate', money.amount);
						//分红失败，预估分红减去分红金额
						break;
					default:
					console.log("8888888888")
						break;
				}

			}

		});

		if(row == 0) {
			return this.fail("修改失败");
		}

		return this.success();

	}

};